package cn.xd.itstack.springframework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import cn.xd.itstack.springframework.beans.BeansException;
import cn.xd.itstack.springframework.beans.factory.DisposableBean;
import cn.xd.itstack.springframework.beans.factory.config.BeanDefinition;
import jdk.nashorn.internal.ir.CallNode;

import java.lang.reflect.Method;

/**
 * @Classname DisposableBeanAdapter
 * @Description 适配器
 * @Date 2022/5/19 上午11:46
 * @Created by lvxiaodong
 */
public class DisposableBeanAdapter implements DisposableBean {

    private Object bean;
    private String beanName;

    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();

    }


    @Override
    public void destroy() throws Exception {
      if(bean instanceof DisposableBean){
          ((DisposableBean) bean).destroy();
      }
      if (StrUtil.isNotBlank(destroyMethodName)){
          Method method = bean.getClass().getMethod(destroyMethodName);
          if(method == null){
              throw new BeansException("Couldn't find a destroy method named '" +
                      destroyMethodName + "' on bean with name '" + beanName + "'");
          }
          method.invoke(bean);

      }
    }
}
